package com.chenzouquan.util.format;

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class YamlFormatter {
    public static void formatYamlFile(String yamlFilePath) {
        try {
            // 读取YAML文件内容
            String yamlContent = new String(Files.readAllBytes(Paths.get(yamlFilePath)));

            // 创建Yaml对象
            Yaml yaml = new Yaml();

            // 解析YAML内容为对象
            Object data = yaml.load(yamlContent);

            // 创建DumperOptions对象，并设置格式化选项
            DumperOptions dumperOptions = new DumperOptions();
            dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            dumperOptions.setPrettyFlow(true);

            // 创建Yaml对象，设置格式化选项
            Yaml formattedYaml = new Yaml(dumperOptions);

            // 将解析后的对象重新转换为格式化后的YAML字符串
            String formattedYamlContent = formattedYaml.dump(data);
            formattedYamlContent = formattedYamlContent.replace("|","").replace("---","");
            // 将格式化后的YAML字符串写回YAML文件
            Files.write(Paths.get(yamlFilePath), formattedYamlContent.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);

            System.out.println("YAML文件格式化成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

